import itertools
import requests
import time
import sys

# ==============================
# 景点及其经纬度数据（纬度在前，经度在后）
# ==============================
scenic_spots = {
    "洪崖洞": (29.5611, 106.5794),
    "解放碑": (29.5572, 106.5772),
    "长江索道": (29.5572, 106.5775),
    "朝天门广场": (29.5670, 106.5878),
    "江北嘴江滩公园": (29.5675, 106.5781),
    "观音桥步行街": (29.5764, 106.5342),
    "人民大礼堂": (29.5617, 106.5536),
    "十八梯": (29.5522, 106.5739),
    "白公馆&渣滓洞": (29.5614, 106.4036),
    "歌乐山革命纪念馆": (29.5722, 106.4422),
    "南山植物园": (29.5564, 106.6322),
    "重庆大剧院": (29.5697, 106.5811),
    "磁器口": (29.5775, 106.4483),
    "重庆建川博物馆": (29.5197, 106.5231),
    "鸿恩寺": (29.5700, 106.5053),
    "鹅岭公园": (29.5497, 106.5361),
    "鹅岭印刷二厂": (29.5508, 106.5406),
    "三峡博物馆": (29.5619, 106.5503),
    "龙门浩": (29.5564, 106.5947),
    "南滨路": (29.5436, 106.5836),
    "金刚碑": (29.8431, 106.4250)
}

# ==============================
# 配置高德 API Key
# ==============================
API_KEY = "6bf23ced3022a0ed65313a402becfa91"
API_URL = "https://restapi.amap.com/v3/direction/driving"

# ==============================
# 生成所有两两组合（210 条路线）
# ==============================
all_pairs = list(itertools.combinations(scenic_spots.items(), 2))

total_tasks = len(all_pairs)

# ==============================
# 调用高德 API 获取驾车距离和耗时
# ==============================
def get_driving_distance(origin, destination, retries=3):
    params = {
        "key": API_KEY,
        "origin": origin,
        "destination": destination
    }
    for attempt in range(retries):
        try:
            r = requests.get(API_URL, params=params, timeout=10)
            data = r.json()
            if data.get("status") == "1":
                paths = data.get("route", {}).get("paths", [])
                if paths:
                    distance = paths[0].get("distance", "未知")
                    duration = paths[0].get("duration", "未知")
                    return distance, duration
            else:
                return "API错误", "API错误"
        except Exception as e:
            time.sleep(1)
    return "请求失败", "请求失败"

# ==============================
# 进度条函数
# ==============================
def print_progress(current, total, bar_length=40):
    fraction = current / total
    filled_length = int(bar_length * fraction)
    bar = "█" * filled_length + "-" * (bar_length - filled_length)
    percent = fraction * 100
    sys.stdout.write(f"\r进度: |{bar}| {percent:6.2f}% ({current}/{total})")
    sys.stdout.flush()

# ==============================
# 输出结果文件 + 统计执行总时长
# ==============================
start_time = time.time()

with open("d4.txt", "w", encoding="utf-8") as f:
    f.write("起点,终点,起点坐标(纬度,经度),终点坐标(纬度,经度),行车距离(米),预计行车时间(秒)\n")

    for i, ((spot1, coord1), (spot2, coord2)) in enumerate(all_pairs, start=1):
        lat1, lng1 = coord1
        lat2, lng2 = coord2

        origin = f"{lng1},{lat1}"       # API 要求经度在前纬度在后
        destination = f"{lng2},{lat2}"

        distance, duration = get_driving_distance(origin, destination)

        f.write(f"{spot1},{spot2},({lat1},{lng1}),({lat2},{lng2}),{distance},{duration}\n")

        # 每次调用间隔 1 秒
        time.sleep(1)

        # 打印进度条
        elapsed = time.time() - start_time
        print_progress(i, total_tasks)

end_time = time.time()

print("\n已生成 d4.txt，包含 210 条路线的实际行车距离和预计行车时间。")
print(f"总计算时长: {end_time - start_time:.2f} 秒")
